<template>
  <div class="row mt-3">
    <div class="col-md-12 col-lg-12">
      <div class="card">
        <div class="card-body">
          <img id="img"class="mx-auto d-block" src="../src/assets/icon.jpg" alt="">
          <form @submit.prevent="onSubmit">
            <div class="form-group">
              <label for="email">邮箱</label>
              <input
                type="email"
                class="form-control"
                v-model="email"
                >
            </div>
            <div class="form-group">
              <label for="password">密码</label>
              <input
                type="password"
                class="form-control"
                v-model="password"
                >
            </div>

            <button type="submit" class="btn btn-block btn-success">登陆</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import  axios   from  'axios';
    export  default  {
       data() {
          return  {
            email:'',
            password:''
          }
       },
       //组件内的守卫
       //在进入路由前进行清除
       beforeRouteEnter:(to,from,next)=> {
           next(vm=>vm.$store.dispatch("setUser",null))
       },
       methods:{
          onSubmit() {
            axios.get('users.json').then(res=>{
               console.log(res.data);
               //将数据库的数据接收储存起来,数据需要过滤，重组
               const  data = res.data;
               //设置一个空数组，接受对象
               const users=[];
               //遍历数据库中的数据，去掉属性，得到数据库值value
               for(let  key  in  data) {
                  const  user = data[key];
                  users.push(user);
               }
               //将用户页面输入的数据与数据库的数据进行匹配
               let result = users.filter((user) => {
                 return user.email === this.email && user.password === this.password;
               })
                //如果匹配 ，就进行跳转.跳转到home页面
               if(result != null && result.length > 0){
                 this.$store.dispatch("setUser",result[0].email)
                 this.$router.push({name:"homeLink"})
               }else{
                 this.$store.dispatch("setUser",null)
                 alert("账号或密码错误!")
               }
               })
          }
       }
    }
</script>
<style media="screen">
    img {
       width: 100px;
       /* height:150px; */
    }
</style>
